package com.zrulin.findcomrade.controller;


import com.zrulin.findcomrade.pojo.User;
import com.zrulin.findcomrade.service.UserService;
import com.zrulin.findcomrade.utils.JWTUtils;
import com.zrulin.findcomrade.vo.Msg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zrulin
 * @create 2021-04-21 21:55
 */
@RestController
@Api(description = "登陆注册")
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation("注册")
    @PostMapping("/register")
    public Msg register(@RequestParam("username") String username,
                        @RequestParam("password") String password){
            User user = userService.queryByUsername(username);
            if(user == null){
                userService.save(new User(username,password));
                return new Msg(200,"注册成功",null);
            }else{
                return new Msg(403,"用户名已存在",null);
            }
    }

    @ApiOperation("登录")
    @PostMapping("/login")
    public Msg login(@RequestParam("username") String username,
                      @RequestParam("password") String password){
        System.out.println(username);
        System.out.println(password);
        User user = userService.queryByUsernameAndPassword(username, password);
        if(user == null){
            return new Msg(404,"密码或用户名错误",null);
        }else{
            String token = JWTUtils.getToken(user.getUsername(), user.getId());
            return new Msg(200,"密码正确",token);
        }
    }
    @ApiOperation("测试，根据用户名查找用户")
    @GetMapping("/user")
    public Msg queryByUsername(@RequestParam("username") String username){
        User user = userService.queryByUsername(username);
        return new Msg(200,user,null);
    }

//    @ApiOperation("验证码")
//    @GetMapping("/code")
//    public void code(HttpServletResponse response, HttpSession session) throws IOException {
//        ServletOutputStream outputStream = response.getOutputStream();
//        SpecCaptcha captcha = new SpecCaptcha(120,40);
//        captcha.setLen(4);
//
//        String result = captcha.text();
//        session.setAttribute("sCode",result);
//        captcha.out(outputStream);
//    }
}
